/*
 * Copyright (c) 2011
 * UNPUBLISHED PROPRIETARY SOURCE CODE.
 */

package com.webservice.service.impl;

import com.webservice.domain.User;
import com.webservice.service.IEmailService;
import org.apache.velocity.app.VelocityEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.ui.velocity.VelocityEngineUtils;

import javax.inject.Inject;
import javax.mail.internet.MimeMessage;
import java.util.HashMap;
import java.util.Map;

/**
 * {@link IEmailService} implementation.
 *
 * @author vkolodrevskiy
 */
@Component
public class EmailService implements IEmailService {
    private static final Logger logger = LoggerFactory.getLogger(EmailService.class);

    private final JavaMailSender mailSender;
    private final VelocityEngine velocityEngine;
    private final Environment environment;

    @Inject
    public EmailService(JavaMailSender mailSender, VelocityEngine velocityEngine, Environment environment) {
        this.mailSender = mailSender;
        this.velocityEngine = velocityEngine;
        this.environment = environment;
    }

    @Async
    @Override
    public void sendWelcomeEmail(final User user) {
        try {
            MimeMessagePreparator preparator = new MimeMessagePreparator() {
                public void prepare(MimeMessage mimeMessage) throws Exception {
                    MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
                    message.setTo(user.getEmail());
                    message.setFrom("webservice@xxx.com"); // could be parameterized...
                    message.setSubject("XXX registration. Welcome.");
                    Map<String, Object> model = new HashMap<String, Object>();
                    model.put("user", user);
                    model.put("appUrl", getAppUrl());
                    String text = VelocityEngineUtils.mergeTemplateIntoString(
                            velocityEngine, "/mail/welcome.vm", model);
                    message.setText(text, true);
                }
            };
            this.mailSender.send(preparator);
            logger.debug("Successfully sent email to [" + user.getEmail() + "]");
        } catch (Exception e) {
            logger.error("Error while sending email: " + e.getLocalizedMessage());
        }
    }

    private String getAppUrl() {
        return environment.getProperty("application.url");
    }
}
